<?php
/**
 * 蜘蛛监控插件 - 服务端许可证验证API
 * 作者：Eric
 * 网站：https://zibovip.top
 */

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 定义插件版本常量（如果不存在）
if (!defined('WP_SPIDER_MONITOR_VERSION')) {
    define('WP_SPIDER_MONITOR_VERSION', '2.0.0');
}

// 远程API通信类 - 不需要本地许可证服务

class Spider_License_Server {
    
    private $use_local_api = false; // 强制使用远程服务端
    private $api_url = 'https://zibovip.top/dingyue/license-api.php';
    private $cache_key = 'spider_license_cache';
    private $cache_duration = 3600; // 1小时缓存
    
    // 备用端点（按优先级排列），支持通过选项或钩子覆盖
    private function get_api_base_urls() {
        $defaults = [
            // 正确的根目录路径（优先级最高）
            'https://zibovip.top/dingyue/license-api.php',
            // 旧版 query 端点
            'https://zibovip.top/wp-content/plugins/spider-monitor/dingyue/license-api.php',
            // REST 端点（示例）
            'https://zibovip.top/wp-json/spider-license/v1'
        ];
        $configured = get_option('spider_license_api_url');
        if (!empty($configured)) {
            array_unshift($defaults, rtrim($configured, '/'));
        }
        // 允许外部通过过滤器覆盖
        $defaults = apply_filters('spider_license_api_base_urls', $defaults);
        // 去重
        $unique = array_values(array_unique(array_map(function($u){ return rtrim($u, '/'); }, $defaults)));
        return $unique;
    }
    
    /**
     * 激活许可证
     */
    public function activate_license($license_key, $domain) {
        // 强制使用远程API
        $response = $this->make_api_request('activate', [
            'license_key' => $license_key,
            'domain' => $domain,
            'ip' => $this->get_client_ip(),
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown',
            'wp_version' => get_bloginfo('version'),
            'plugin_version' => WP_SPIDER_MONITOR_VERSION
        ]);
        // 成功时补充短时效签名票据
        if (is_array($response) && !empty($response['success'])) {
            $response = $this->append_signed_token($response, $license_key, $domain);
        }
        return $response;
    }
    
    /**
     * 验证许可证状态
     */
    public function verify_license($license_key, $domain) {
        // 强制使用远程API
        $response = $this->make_api_request('verify', [
            'license_key' => $license_key,
            'domain' => $domain,
            'ip' => $this->get_client_ip()
        ]);
        if (is_array($response) && !empty($response['success'])) {
            $response = $this->append_signed_token($response, $license_key, $domain);
        }
        return $response;
    }
    
    /**
     * 检查功能权限
     */
    public function check_feature_access($license_key, $domain, $feature) {
        // 强制使用远程API
        $response = $this->make_api_request('check-feature', [
            'license_key' => $license_key,
            'domain' => $domain,
            'feature' => $feature
        ]);
        
        return $response;
    }
    
    /**
     * 获取许可证详情
     */
    public function get_license_details($license_key, $domain) {
        // 强制使用远程API
        $response = $this->make_api_request('details', [
            'license_key' => $license_key,
            'domain' => $domain
        ]);
        if (is_array($response) && !empty($response['success'])) {
            $response = $this->append_signed_token($response, $license_key, $domain);
        }
        return $response;
    }
    
    /**
     * 停用许可证
     */
    public function deactivate_license($license_key, $domain) {
        // 强制使用远程API
        $response = $this->make_api_request('deactivate', [
            'license_key' => $license_key,
            'domain' => $domain
        ]);
        
        return $response;
    }

    // 生成并附加短时效签名票据
    private function append_signed_token($response, $license_key, $domain) {
        // 从远端返回中获取计划/到期时间（可选）
        $plan = is_array($response) && isset($response['plan']) ? $response['plan'] : 'pro';
        $expires_at = is_array($response) && !empty($response['expires_at']) ? strtotime($response['expires_at']) : 0;
        $token = $this->build_signed_token($license_key, $domain, $plan, $expires_at);
        if ($token) {
            $response['token'] = $token;
        }
        return $response;
    }

    private function build_signed_token($license_key, $domain, $plan, $remoteExpiresTs = 0) {
        $secret = get_option('spider_license_shared_secret');
        if (empty($secret)) { return null; }
        $now = time();
        // token 最长15分钟；若远端有到期时间，取二者较早者
        $localExp = $now + 10 * 60; // 10分钟默认
        if ($remoteExpiresTs > 0) { $localExp = min($localExp, $remoteExpiresTs); }
        $data = [
            'license_key' => strval($license_key),
            'domain' => strval($domain),
            'plan' => strval($plan ?: 'pro'),
            'exp' => $localExp,
            'ts' => $now,
            'nonce' => wp_generate_password(8, false)
        ];
        ksort($data);
        $payload = http_build_query($data, '', '&', PHP_QUERY_RFC3986);
        $data['sig'] = hash_hmac('sha256', $payload, $secret);
        return $data;
    }
    
    /**
     * 获取API文档
     */
    public function get_api_documentation() {
        return [
            'api' => 'Spider Monitor License API',
            'version' => '1.0.0',
            'mode' => '远程服务端模式',
            'description' => '客户端许可证验证 - 强制使用远程服务端',
            'endpoints' => [
                'POST https://zibovip.top/dingyue/license-api.php?action=activate' => '激活许可证',
                'POST https://zibovip.top/dingyue/license-api.php?action=verify' => '验证许可证',
                'POST https://zibovip.top/dingyue/license-api.php?action=deactivate' => '停用许可证',
                'POST https://zibovip.top/dingyue/license-api.php?action=check-feature' => '检查功能权限'
            ],
            'parameters' => [
                'license_key' => '许可证密钥',
                'domain' => '激活域名',
                'ip' => '客户端IP（可选）',
                'user_agent' => '用户代理（可选）',
                'feature' => '功能名称（check-feature时必需）'
            ],
            'example_usage' => [
                'activate' => 'POST https://zibovip.top/wp-json/spider-license/v1/activate',
                'verify' => 'POST https://zibovip.top/wp-json/spider-license/v1/verify',
                'check_feature' => 'POST https://zibovip.top/wp-json/spider-license/v1/check-feature'
            ]
        ];
    }
    
    /**
     * 远程API请求
     */
    private function make_api_request($endpoint, $data) {
        // 追加签名字段（可选）
        $secret = get_option('spider_license_shared_secret');
        $data['ts'] = time();
        $data['nonce'] = wp_generate_password(8, false);
        if (!empty($secret)) {
            ksort($data);
            $payload = http_build_query($data, '', '&', PHP_QUERY_RFC3986);
            $data['sig'] = hash_hmac('sha256', $payload, $secret);
        }
        $base_urls = $this->get_api_base_urls();
        $last_error = null;
        
        foreach ($base_urls as $base) {
            // 根据基地址类型决定 URL 组合方式
            if (stripos($base, '/wp-json/spider-license/v1') !== false) {
                // REST 风格：/wp-json/spider-license/v1/{endpoint}
                $url = rtrim($base, '/') . '/' . $endpoint;
            } else {
                // 传统 query 风格：license-api.php?action={endpoint}
                $url = rtrim($base, '/') . '?action=' . $endpoint;
            }

            $args = [
                'body' => $data,
                'timeout' => 15,
                'headers' => [
                    'Content-Type' => 'application/x-www-form-urlencoded',
                    'Accept' => 'application/json, */*;q=0.1',
                    'User-Agent' => 'WordPress Spider Monitor/' . WP_SPIDER_MONITOR_VERSION
                ]
            ];

            $response = wp_remote_post($url, $args);

            if (is_wp_error($response)) {
                $last_error = '连接失败(' . $url . '): ' . $response->get_error_message();
                continue; // 尝试下一个端点
            }

            $status = wp_remote_retrieve_response_code($response);
            $body = wp_remote_retrieve_body($response);

            // 去除 UTF-8 BOM
            if (substr($body, 0, 3) === "\xEF\xBB\xBF") {
                $body = substr($body, 3);
            }
            // 某些服务器会在前后加入空白/注释
            $body_trimmed = trim($body);

            // 优先解析 JSON
            $decoded = json_decode($body_trimmed, true);

            if ($status !== 200) {
                // 如非 200，则记录并尝试下一个端点
                $last_error = 'HTTP ' . $status . ' (' . $url . '): ' . substr($body_trimmed, 0, 200);
                continue;
            }

            if (is_array($decoded)) {
                return $decoded; // 成功
            }

            // 如果返回 HTML（如 404 页面），换下一个端点
            if (stripos($body_trimmed, '<!DOCTYPE html') !== false || stripos($body_trimmed, '<html') !== false) {
                $last_error = '收到HTML响应(' . $url . '): ' . substr($body_trimmed, 0, 200);
                continue;
            }

            // 其他非JSON响应
            $last_error = '无效响应(' . $url . '): ' . substr($body_trimmed, 0, 200);
        }

        // 所有端点均失败
        if ($last_error) {
            error_log('Spider License API Error - ' . $last_error);
        }
        // 对于停用操作，允许本地兜底成功，避免用户被卡死
        if ($endpoint === 'deactivate') {
            return [
                'success' => true,
                'message' => '远程端点不可用，已本地停用许可证',
                'fallback' => true
            ];
        }
        
        return [
            'success' => false,
            'message' => '服务器返回数据格式错误或端点不可用：' . ($last_error ?: '未知错误')
        ];
    }
    
    /**
     * 获取客户端IP（公共方法）
     */
    public function get_client_ip() {
        $ip_keys = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'];
        foreach ($ip_keys as $key) {
            if (!empty($_SERVER[$key])) {
                $ip = explode(',', $_SERVER[$key])[0];
                $ip = trim($ip);
                if (filter_var($ip, FILTER_VALIDATE_IP)) {
                    return $ip;
                }
            }
        }
        return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    }
}

// 全局实例
$GLOBALS['spider_license_server'] = new Spider_License_Server();